;(function($, window, document, undefined){

    // "use strict";
    var PLUGIN_NAME = "Panel";
    $[PLUGIN_NAME] = $[PLUGIN_NAME] || {};
    $[PLUGIN_NAME] = function(){
        this.opened = { /* flag:panelObj */ };
        this.maxIndex = 10001;
        this.singleOpened = { /* id: panelObj */ };
        
        // options = { type:0, title:"", content:"",width:number, height: number,
        // shadow:true, btns:[''],cmds:[function], fixPosition:false, single:bool--onlyiframe--byid,id:"",}
        // type--0-info  1--iframe
        this.open = function(options){
            // single判断
            // 判断是否已经打开
            if(options.single && options.single == true && options.id){
                if(options.id in this.singleOpened){
                    var _flag = this.singleOpened[options.id].flag;
                    if(this.singleOpened[options.id].state == 'hide'){
                        this.show(_flag);
                    }
                    return _flag;
                }
            }

            var obj = new panelObj(this, ++this.maxIndex, options);
            var flag = obj.open();
            this.opened[''+flag] = obj;
            // single处理
            if(options.single && options.single == true && options.id){
                this.singleOpened[options.id] = obj;
            }

            this.maxIndex = this.maxIndex +2;
            return flag;
        };
        this.show = function(flag){
            $("."+flag).fadeIn();
            $("."+flag+"_shadow").fadeIn();
            try{
                this.opened[flag].state = "open";
            }catch(e){}         
        }

        this.hide = function(flag){
            $("."+flag).fadeOut();            
            $("."+flag+"_shadow").fadeOut();
            try{
                this.opened[flag].state = "hide";
            }catch(e){}         
        }

        // 强制关闭，不进行回调
        this.close = function(flag){
            this.hide(flag);
            setTimeout(function(){
                $("."+flag).remove();          
                $("."+flag+"_shadow").remove();    
            }, 300);
            this.onPanelClose(flag);
        }

        // 事件
        this.onPanelClose = function(flag){
            try{
                if(this.opened[flag].options.single == true && this.opened[flag].options.id){
                    delete this.singleOpened[this.opened[flag].options.id];
                }
            }catch(e){}
            delete this.opened[flag];
        }


        //{content:"",ok:function}
        this.alert = function(content, callback){
            this.open({type: 0, content: content, btns:['确定'], cmds:[callback]});
        }

        return this;
    };


    
    var defaultOptions = {
        type: 0, //info
        title: '信息', 
        width: 300,
        height: 80,
        btns: ['确定', '取消'],
        cmds: [function(){
            // if(console && console.log){
            //     console.log("panel event","you clicked ok");
            // }
        },function(){
            // if(console && console.log){
            //     console.log("panel event","you clicked cancel");
            // }
        }],
        onClose: function(){
            // if(console && console.log){
            //     console.log("panel event","you clicked close");
            // }
        },
        shadow: true,
        fixPosition: true
    };


    function panelObj(manager, index, options){


        // 函数
        /*-------------------------- +
        改变大小函数
        +-------------------------- */
        this.resize = function(oParent, handle, isLeft, isTop, lockX, lockY) {

                var that = this;
                $(handle).mousedown ( function (event){

                    that.resetZIndex();
                    // 显示父控件遮罩层
                    if(that.options.shadow == false){
                        that.$shadow.css({
                            "background": "rgba(0,0,0,0.01)",
                            "display": "block"
                        });
                    }
                
                    // 显示子控件遮罩层
                    that.$root.append(that.$contentShadow);

                    var event = event || window.event;
                    var sx = event.clientX;
                    var sy = event.clientY;

                    var spw = $(oParent).width();
                    var sph = $(oParent).height();
                    var spt = $(oParent).offset().top;
                    var spl = $(oParent).offset().left;

                    function onMove(event) {
                        var event = event || window.event;
                        var ex = event.clientX;
                        var ey = event.clientY;
                        
                        if(ex > document.documentElement.clientWidth - 8){
                            ex = document.documentElement.clientWidth - 8;
                        }
                        if(ey > document.documentElement.clientHeight - 8 ){
                            ey = document.documentElement.clientHeight - 8;
                        }

                        $(oParent).css({
                            "width": spw + (ex - sx) + "px",
                            "height": sph + (ey - sy) + "px"
                        });
                        
                    }

                    function onMouseUp(){
                        // 显示父控件遮罩层
                        if(that.options.shadow == false){
                            that.$shadow.css({
                                "background": "transparent",
                                "display": "none"
                            });
                        }
                    
                        // 显示子控件遮罩层
                        that.$contentShadow.remove();

                        $(document).unbind('mousemove', onMove);
                        $(document).unbind('mouseup', onMouseUp);
                        // $(window).focus();
                    }

                    $(document).mousemove(onMove);
                    $(document).mouseup(onMouseUp);

                    return false;
                });
            };

        // 获取用户定义的样式
        this.getDialogStyle = function () {
            if(this.options.type!=1) return null;
            try {
                var url = this.options.content;
                var res = $.ajax({ url: url, async: false,cache: false, type: "get", dataType: "xml" });
                res = res.responseText;
                var index = res.indexOf("dialog_style");
                if (index > -1) {
                    res = res.substring(index);
                    res = res.substring(0, res.indexOf("/script>") - 1);
                    res = res.substring(res.indexOf('{'));
                    res = res.substring(0, res.lastIndexOf('}') + 1);
                    var styleObjs = eval('[' + res + ']');// eval('oo=' + res);
                    var styleObj = styleObjs[0];
                    return styleObj;
                    
                }
                return null;
            } catch (e) { return null; }
        };

        this.resetZIndex = function(){
            ++manager.maxIndex;
            this.$shadow.css({ 'z-index': ++manager.maxIndex });
            this.$root.css({ 'z-index': ++manager.maxIndex });
        }
       



        var that = this;
        this.options = $.extend({}, defaultOptions, options);
        this.flag = _getNewFlag('mng');

        this.state = "creating"; // 'open', 'hide', 'min', 'max'

        this.sizeBeforeAnimate = {
            width: 300,
            height: 30
        };

        // $shadow 修改为都要增加，根据shadow值判断display 和 background 属性。
        // 因为panel父控件中有iframe时，会导致拖动时、resize时有卡顿。
        // 初始化时，透明，不显示
        this.$shadow = $("");
        // if(this.options.shadow){
            this.$shadow = $("<div>").css({
                "position": "fixed",
                "left": "0",
                "top": "0",
                "right": "0",
                "bottom": "0",
                "z-index": ++index,
                "background": "transparent", //"rgba(0,0,0,0.1)"
                "display": "none"
            }).addClass(this.flag+"_shadow");
        // }

        this.$root = $("<div>").addClass(this.flag)
                                .addClass("__panel__root")
                                .css({
                                    "z-index": ++index
                                });
                                // .addClass("showPanel")
                                // .attr("data-animation", "layerFadeIn");

        this.$header = $("<div>").addClass("__panel__header");
        this.$title = $("<div>").addClass("__panel__title");
        this.$rootClose = $("<span>").addClass("__panel__title_cmd").addClass("__panel__close").html("×");
        this.$rootMin = $("<span>").addClass("__panel__title_cmd").addClass("__panel__min").html("-");
        this.$rootMax = $("<span>").addClass("__panel__title_cmd").addClass("__panel__max").html("□");

        this.$rootMax.css({"display":"none"});
        

        this.$header.append(this.$title).append(this.$rootClose);
        this.$header.append(this.$title).append(this.$rootMin);
        this.$header.append(this.$title).append(this.$rootMax);
        
        // events
        this.$rootClose.click(function(){
            if(that.options.onClose && typeof that.options.onClose == 'function'){
                that.options.onClose();
            }
            that.close();
        });

        this.$rootMin.click(function(){
            that.sizeBeforeAnimate.width = that.$root.width();
            that.sizeBeforeAnimate.height = that.$root.height();
            
            
            that.$root.animate({ height: "30px"}, 250,  function(){
                that.$root.animate({ width: "120px"}, 250,  function(){
                    that.$rootMin.css({"display":"none"});
                    that.$resizeEle.css({"display": "none"});
                    that.$rootMax.css({"display":"block"});
                    that.state = "min";
                });
            });
            
            
        });

        this.$rootMax.click(function(){

            that.$root.animate({ height: that.sizeBeforeAnimate.height + "px"}, 250, function(){
                that.$root.animate({ width: that.sizeBeforeAnimate.width + "px"}, 250, function(){
                    that.$rootMax.css({"display":"none"});
                    that.$resizeEle.css({"display": "block"});
                    that.$rootMin.css({"display":"block"});
                    that.state = "max";
                });
            });
            
        });

        this.close = function(){
            that.$root.fadeOut();
            that.$shadow.fadeOut();
            
            setTimeout(function(){
                that.$root.remove();
                that.$shadow.remove();
                manager.onPanelClose(that.flag);
            }, 300);
        }

        // ---------- footer  content
        this.$content = $("<div>").addClass("__panel__content");
        this.$contentShadow = $("<div>").addClass("__panel__content_shadow")
            .css({
                "position": "absolute",
                "top": "30px",
                "right": "0",
                "bottom": "0",
                "left": "0",
                "opacity": "0"
            });
        
        this.$footer = $("");
        if(this.options.type == 0){ // info 

            // 隐藏minmax按钮
            this.$rootMin.css({"display":"none"});
            this.$root.css({"min-height":"120px"});

            this.$footer = $("<div>").addClass("__panel_footer");
            for(var i=0;i<this.options.btns.length;i++){
                var $btn = $("<span>");
                $btn.addClass("__panel_btn")
                    .attr("data-idx", i)
                    .addClass("btn")
                    .addClass(i==0?"btn-dark":"btn-light")
                    .html(this.options.btns[i]).appendTo(this.$footer);
                    
                $btn.click(function(e){
                    var cmd = that.options.cmds[e.target.getAttribute('data-idx')]; // IE9不支持 e.target.dataset.idx 写法
                    if(cmd && typeof cmd == 'function'){
                        var _willclose = cmd(that.flag);

                        // 没有返回值默认关闭。只有返回false的情况下才不关闭弹窗
                        if(_willclose != false){
                            that.close();
                        }
                    }else{
                        // 没有回调函数就关闭
                        that.close();
                    }
                });
                
            }

            // alert 情况下，按钮居中
            if(this.options.btns.length == 1){
                this.$footer.css({
                    "padding": "0",
                    "text-align": "center"
                });
            }

            this.$contentRoot = $("<table>").append($("<tr>").append($("<td>").html(this.options.content)))
                .css({width:'100%',height:'100%'});
            this.$content.append(this.$contentRoot);
            this.$content.css({
                'text-align':'center'
            });

        } else if(this.options.type == 1){ //iframe
            this.$frame = $("<iframe>").css({
                "position": "absolute",
                "top": "0",
                "right": "0",
                "bottom": "0",
                "left": "0",
                "width": "100%",
                "height": "100%",
                // "background": "gray",
                "border": "0px",
                "outline": "none"
            }).attr("src", this.options.content).addClass("__panel__frame");

            var _style = this.getDialogStyle();
            if(_style != null){
                this.options = $.extend({}, this.options, _style);
            }

            this.$content.css({
                "bottom": "0"
            }).append(this.$frame);
        }


        this.$resizeEle = $("<div>").css({
            "position": "absolute",
            "width": "8px",
            "height": "8px",
            "right": "0px",
            "bottom": "0px",
            "cursor": "nw-resize",
            "user-select": "none",
            "background": "rgba(255,255,255,0.01)"  //transparent  IE9透明可能鼠标选取不到
        });

        

        

       // drag move
        if(true){ 
            this.$header.mouseover(function(){
                $(this).css("cursor","move")
            }).mousedown(function(e1){

                that.resetZIndex();
                // 显示父控件遮罩层
                if(that.options.shadow == false){
                    that.$shadow.css({
                        "background": "rgba(0,0,0,0.01)",
                        "display": "block"
                    });
                }
                
                // 显示子控件遮罩层
                that.$root.append(that.$contentShadow);

                e1 = e1 || window.event;
                var isMove = true; 

                var sl = that.$root.offset().left;
                var st = that.$root.offset().top;
                var sx = e1.clientX;
                var sy = e1.clientY;

                var soffsetY = e1.offsetY;

                $(document).mousemove(function (e) { 
                    if (isMove) { 

                        that.$root.css({"opacity": "0.5"});

                        var ex = e.clientX;
                        var ey = e.clientY - soffsetY < 0 ? soffsetY : e.clientY;
                        if(e.clientY+(that.$root.height() - soffsetY) > document.documentElement.clientHeight){
                            ey = document.documentElement.clientHeight - (that.$root.height() - soffsetY);
                        }

                        var el = sl + (ex - sx);
                        var et = st + (ey - sy);
                        
                        if(el < 0 ){
                            el = 0;
                        }else if(el > document.documentElement.clientWidth - that.$root.width() - 8 ){
                            el = document.documentElement.clientWidth - that.$root.width() - 8;
                        }

                        that.$root.offset({ left:el,  top:et })
                            .css({"margin-left":0,"margin-top":0}); 	
                    } 
                }).mouseup(function(){
                    that.$root.css({"opacity": "1"});
                    // 隐藏父控件遮罩层
                    if(that.options.shadow == false){
                        that.$shadow.css({
                            "background": "transparent",
                            "display": "none"
                        });
                    }
                    that.$contentShadow.remove();
                    isMove = false;
                });


            });
        }




        // 设置显示的几个参数
        this.applyParams = function(){
            // title
            this.$title.html(this.options.title);
            // width, height
            if(this.options.width){
                this.$root.css({"width":this.options.width + 20 + "px"}); //20滚动条
            }
            if(this.options.height){
                this.$root.css({"height":this.options.height + (this.options.type==1?30:80)+"px"});
            }
        }
        

        this.open = function(){
            var that = this;
            this.applyParams();
            $("body").append(
                this.$root.append(this.$header)
                .append(this.$content)
                .append(this.$footer)
                .append(this.$resizeEle)
            ).append(this.$shadow);

            // 显示遮罩层
            if(this.options.shadow){
                this.$shadow.css({
                    "background": "rgba(0,0,0,0.1)",
                    "display": "block"
                });
            }

            // 向iframe传递参数
            if(this.$frame && this.options && this.options.params){
                this.$frame[0].onload = function(){
                    this.contentWindow._data = that.options.params; 
                }
            }

            function setPosition(){
                that.$root.css({
                    "top": (document.documentElement.clientHeight - that.$root.height())*0.5 + "px",
                    "left": (document.documentElement.clientWidth - that.$root.width())*0.5 + "px"
                });
            }

            $(this.$root[0]).click(function(){
                that.resetZIndex();
            });
            $(this.$root[0].children).click(function(){
                that.resetZIndex();
            });
            // $(this.$frame[0]).click(function(){
            //     that.resetZIndex();
            // });
            $.each(document.getElementsByClassName("__panel__frame"), function(index, ele){
                ele.addEventListener("click", function(){
                    that.resetZIndex();
                }, true);
            });
            
            setPosition();
            if(this.options.fixPosition){
                $(window).resize(setPosition);
            }
            
            this.resize(this.$root, this.$resizeEle, false, false, false, false);
            this.state = "open";
            return this.flag;
        }

        return this;
    }


    // 私有函数
    var ii=0;
    function _getNewFlag(flag){
        var f = '__panel__' + (ii++) + '_' + flag + '_'
                 + (new Date()).getTime() 
                 + parseInt(Math.random()*100000);
        if($('#'+f).length > 0){
            return _getNewFlag(flag);
        }else{
            return f;
        }
    }
    

})(jQuery, window, document);